<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="面积" prop="area">
        <el-input v-model="formData.area" placeholder="请输入面积" />
      </el-form-item>
      <el-form-item label="房型" prop="houseType">
        <el-input v-model="formData.houseType" placeholder="请输入房型" />
      </el-form-item>
      <el-form-item label="拍卖方式" prop="auctionNumber">
        <el-select v-model="formData.auctionNumber" placeholder="请选择拍卖方式">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.AUCTION_METHOD)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="市场价" prop="marketPrice">
        <el-input v-model="formData.marketPrice" placeholder="请输入市场价" />
      </el-form-item>
      <el-form-item label="市场单价" prop="marketUnitPrice">
        <el-input v-model="formData.marketUnitPrice" placeholder="请输入市场单价" />
      </el-form-item>
      <el-form-item label="捡漏空间价格" prop="pickupSpacePrice">
        <el-input v-model="formData.pickupSpacePrice" placeholder="请输入捡漏空间价格" />
      </el-form-item>
      <el-form-item label="起拍价" prop="startingPrice">
        <el-input v-model="formData.startingPrice" placeholder="请输入起拍价" />
      </el-form-item>
      <el-form-item label="起拍单价" prop="startingOddPrice">
        <el-input v-model="formData.startingOddPrice" placeholder="请输入起拍单价" />
      </el-form-item>
      <el-form-item label="折扣" prop="discount">
        <el-input v-model="formData.discount" placeholder="请输入折扣" />
      </el-form-item>
      <el-form-item label="小区名称" prop="cellName">
        <el-input v-model="formData.cellName" placeholder="请输入小区名称" />
      </el-form-item>
      <el-form-item label="梯步" prop="step">
        <el-input v-model="formData.step" placeholder="请输入梯步：电梯、楼梯" />
      </el-form-item>
      <el-form-item label="楼层" prop="floor">
        <el-input v-model="formData.floor" placeholder="请输入楼层" />
      </el-form-item>
      <el-form-item label="物业类型" prop="propertyType">
        <el-input v-model="formData.propertyType" placeholder="请输入物业类型" />
      </el-form-item>
      <el-form-item label="拍卖次数" prop="numberOfAuctions">
        <el-input type="number" v-model="formData.numberOfAuctions" placeholder="请输入拍卖次数" />
      </el-form-item>
      <el-form-item label="保证金" prop="earnestMoney">
        <el-input v-model="formData.earnestMoney" placeholder="请输入保证金" />
      </el-form-item>
      <el-form-item label="加价幅度" prop="bidIncrement">
        <el-input v-model="formData.bidIncrement" placeholder="请输入加价幅度" />
      </el-form-item>
      <el-form-item label="折扣率" prop="discountRate">
        <el-input v-model="formData.discountRate" placeholder="请输入折扣率" />
      </el-form-item>
      <el-form-item label="建筑年份" prop="architectureYear">
        <el-input v-model="formData.architectureYear" placeholder="请输入建筑年份" />
      </el-form-item>
      <el-form-item label="装修情况" prop="decorateSituation">
        <el-input v-model="formData.decorateSituation" placeholder="请输入装修情况" />
      </el-form-item>
      <el-form-item label="省市区" prop="address">
        <el-input v-model="formData.address" placeholder="请输入省市区" />
      </el-form-item>
<!--      <el-form-item label="区" prop="district">-->
<!--        <el-input v-model="formData.district" placeholder="请输入区" />-->
<!--      </el-form-item>-->
 <el-form-item label="选取地图位置">
        <el-button type="primary" @click="mapDialogVisible = true">获取</el-button>
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input v-model="formData.longitude" placeholder="请输入经度" />
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input v-model="formData.latitude" placeholder="请输入纬度" />
      </el-form-item>
      <el-form-item label="图片详情" prop="detailList"> <UploadImgs v-model="formData.detailList" />
       
      </el-form-item>
      <el-form-item label="轮播图片详情" prop="coverPicList">
		   <UploadImgs v-model="formData.coverPicList" />
        
      </el-form-item>
	  <!-- formData.backgroundPic -->
	
	  
      <el-form-item label="封面/背景图" prop="backgroundPic">
		   <UploadImg v-model="formData.backgroundPic" />
       
      </el-form-item>
<!--      <el-form-item label="详情表图" prop="infoTable">-->
<!--		   <UploadImg v-model="formData.infoTable" />-->
<!--      -->
<!--      </el-form-item>-->
<!--      <el-form-item label="拍卖状态" prop="auctionState">-->
<!--        <el-select v-model="formData.auctionState" clearable  placeholder="请选择拍卖状态" >-->
<!--          <el-option-->
<!--            v-for="dict in getStrDictOptions(DICT_TYPE.AUCTION_STATE)"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <el-form-item label="拍卖状态" prop="status">
        <el-select v-model="formData.auctionState" clearable placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.AUCTION_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="房源类型（住宅/商业）" prop="housingType">
        <el-select v-model="formData.housingType" clearable placeholder="请选择房源类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.HOUSING_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="电话" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入电话" />
      </el-form-item>
      <el-form-item label="起拍时间" prop="auctionTime">
        <el-date-picker
          v-model="formData.auctionTime"
          type="datetime"
          placeholder="请选择起拍时间"
          format="YYYY/MM/DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
	<el-dialog
	  v-model="mapDialogVisible"
	  title="获取经纬度"
	  append-to-body
	  width="500px"
	  class="mapBox"
	>
	  <iframe id="mapPage" width="100%" height="100%" frameborder="0" :src="tencentLbsUrl"></iframe>
	</el-dialog>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from "@/utils/dict";
import * as HousingResourceApi from '@/api/hutai/housingResource'
import * as ConfigApi from '@/api/infra/config'
import { getAreaTree } from '@/api/system/area'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const mapDialogVisible = ref(false) // 地图弹窗的是否展示
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: undefined,
  area: undefined,
  houseType: undefined,
  auctionNumber: undefined,
  marketPrice: undefined,
  marketUnitPrice: undefined,
  pickupSpacePrice: undefined,
  startingPrice: undefined,
  startingOddPrice: undefined,
  discount: undefined,
  cellName: undefined,
  step: undefined,
  floor: undefined,
  propertyType: undefined,
  numberOfAuctions: undefined,
  earnestMoney: undefined,
  bidIncrement: undefined,
  discountRate: undefined,
  architectureYear: undefined,
  decorateSituation: undefined,
  address: undefined,
  district: undefined,
  longitude: undefined,
  latitude: undefined,
  detailPic: undefined,
  coverPic: undefined,
  infoTable: undefined,
  backgroundPic: undefined,
  auctionState: undefined,
  auctionTime: undefined,
  mobile: undefined,
  housingType: undefined

})
//const auctionStatelist = ref(['等待拍卖','竞拍中','已结束'])
const formRules = reactive({
})
const formRef = ref() // 表单 Ref
const areaList = ref() // 区域树
const tencentLbsUrl = ref('') // 腾讯位置服务 url

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
     let Data = await HousingResourceApi.getHousingResource(id)
	   formData.value = await HousingResourceApi.getHousingResource(id)
	  // formData.value.auctionState=auctionStatelist.value[Data.auctionState]
	 let arrpiclist = Data.coverPicList.map((items, j) => {
	  		return  {
				uid:j,
				url:items
			}
	  		
	  	})
		
	let detaipic = Data.detailList.map((items, j) => {
	 		return  {
					uid:j,
					url:items
				}
	 		
	 	})
	 formData.value.coverPicList = arrpiclist
	 
	   formData.value.detailList = detaipic
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const handlePreview= async (file) =>{
        console.log(file);
      }
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  	if(formData.value.detailList){
let urlArr = formData.value.detailList.map((item, i) => {
	
		return   {
			url:item.url
		} 
		
	})
	formData.value.detailLists = urlArr;
	}
	if(formData.value.coverPicList){
let coverPicArr = formData.value.coverPicList.map((items, j) => {

		return {
			url:items.url
		} 
		
	})
	formData.value.coverPicLists = coverPicArr;	
	}

  try {
    const data = formData.value as unknown as HousingResourceApi.HousingResourceVO
	

    if (formType.value === 'create') {
      await HousingResourceApi.createHousingResource(data)
      message.success(t('common.createSuccess'))
    } else {
      await HousingResourceApi.updateHousingResource(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
/** 选择经纬度 */
const selectAddress = function (loc: any): void {
  if (loc.latlng && loc.latlng.lat) {
    formData.value.latitude = loc.latlng.lat
  }
  if (loc.latlng && loc.latlng.lng) {
    formData.value.longitude = loc.latlng.lng
  }
  mapDialogVisible.value = false
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: undefined,
    area: undefined,
    houseType: undefined,
    auctionNumber: undefined,
    marketPrice: undefined,
    marketUnitPrice: undefined,
    pickupSpacePrice: undefined,
    startingPrice: undefined,
    startingOddPrice: undefined,
    discount: undefined,
    cellName: undefined,
    step: undefined,
    floor: undefined,
    propertyType: undefined,
    numberOfAuctions: undefined,
    earnestMoney: undefined,
    bidIncrement: undefined,
    discountRate: undefined,
    architectureYear: undefined,
    decorateSituation: undefined,
    address: undefined,
    district: undefined,
    longitude: undefined,
    latitude: undefined,
    detailPic: undefined,
    coverPic: undefined,
    infoTable: undefined,
    backgroundPic: undefined,
    auctionState: undefined,
    auctionTime: undefined,
    mobile: undefined
  }
  formRef.value?.resetFields()
}


/** 初始化数据 */
const initData = async () => {
  formLoading.value = true
  try {
    const data = await getAreaTree()
    areaList.value = data
  } finally {
    formLoading.value = false
  }
  // TODO @jason：要不创建一个 initTencentLbsMap
  window.selectAddress = selectAddress
  window.addEventListener(
    'message',
    function (event) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      let loc = event.data
      if (loc && loc.module === 'locationPicker') {
        // 防止其他应用也会向该页面 post 信息，需判断 module 是否为 'locationPicker'
        window.parent.selectAddress(loc)
      }
    },
    false
  )
  const data = await ConfigApi.getConfigKey('tencent.lbs.key')
  let key = ''
  if (data && data.length > 0) {
    key = data
  }
  tencentLbsUrl.value = `https://apis.map.qq.com/tools/locpicker?type=1&key=${key}&referer=myapp`
}

/** 初始化 **/
onMounted(() => {
  initData()
})



</script>
<style lang="scss">
.mapBox .el-dialog__body {
  height: 640px !important;
}
</style>
